package connections;

import java.util.Vector;

import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.TextField;

import util.Preferences;
import util.Storage;
import connectionSettings.BTSerialConnectionSettings;
import connectionSettings.ConnectionSettings;
import connectionSettings.HttpConnectionSettings;
import connectionSettings.SocketConnectionSettings;

//

public class Uploader extends Form implements CommandListener, ItemStateListener, ConnectionListener {

	public static int NO_INSERTION_IN_FILENAME = 0;

	public static int INSERT_TIMESTAMP_IN_FILENAME = 1;

	public static int INSERT_TIMESTAMP_METADATA_IN_FILENAME = 2;

	public static int TIMESTAMP_CONTENTS_METADATA_RAW_BYTES = 0;

	public static int CONTENTS_METADATA_RAW_BYTES = 1;

	public static int CONTENTS_RAW_BYTES = 2;

	public static int TIMESTAMP_CONTENTS_METADATA_ASCII = 3;

	public static int CONTENTS_METADATA_SEPARATE_FILES = 4;

	Connection uploadConnection;

	ConnectionSettings connectionForm;

	int mode = 0;

	ChoiceGroup uploadStyle;

	ChoiceGroup filenameInsertionChoice;

	ChoiceGroup contentFormattingChoice;

	int contentFormattingStyle =TIMESTAMP_CONTENTS_METADATA_ASCII;

	int filenameInsertionStyle;

	ChoiceGroup connectionType;

	TextField chunkSize;

	int uploads = 0;

	byte[] uploadArray;

	int packetSize = 1000;

	boolean allowBunching = true;

	String[] packingSlip;

	// boolean timeStampRecordBin;

	// boolean timeStampRecordAscii;

	// boolean metadataFile;

	// boolean metadataRecordBin;

	// boolean metadataRecordAscii;

	// boolean metadataSeparateFile;

	// boolean timeStampFile;

	boolean append = true;

	int placeInUploadArray = 0;

	int totalPackets;

	int packetNumber;

	boolean sendingFragments = false;

	boolean sendingRecords;

	Display midletDisplay;

	Displayable revertToForm;

	Storage myStorage;

	byte[] myByteArray;

	int recordBeingSent;

	TextField fileNameBox;

	// String adjustedFilename = "None";

	String baseFilename = "None";

	Preferences prefs;

	// int SENDING_HTTP =1 ;
	// int SENDING_SOCKET =2;
	// int SENDING_BT =3;

	public Uploader(Display _d) {
		super("Uploader");
		getPrefs();
		showInterface();
		midletDisplay = _d;
		revertToForm = midletDisplay.getCurrent();
		midletDisplay.setCurrent(this);
	}

	public Uploader(Display _d, byte[] _b, String _filename) {
		super("Uploader");
		getPrefs();
		showInterface();
		fileNameBox.setString(_filename);
		midletDisplay = _d;
		revertToForm = midletDisplay.getCurrent();
		midletDisplay.setCurrent(this);
		myByteArray = _b;
	}

	public Uploader(Display _d, Storage _rs) {
		super("Uploader");
		myStorage = _rs;
		getPrefs();
		showInterface();

		midletDisplay = _d;
		revertToForm = midletDisplay.getCurrent();
		midletDisplay.setCurrent(this);

	}
	
	public String combineStringArray(String[] _parts, String _delim) {
		String combo = "";
		String delim = "";
		for (int i = 0; i < _parts.length; i++) {
			combo = combo + delim + _parts[i];
			delim = _delim;
		}
		return combo;
	}
	
	public void commandAction(Command _c, Displayable _d) {

		if (_c.getLabel().equals("Exit")){
			midletDisplay.setCurrent(revertToForm);
		}else if (_c.getLabel().equals("Preferences")){
			showProtocolOptions();
		}
		
	}
	   public void deleteAll(){
		  // try{
			for(int i = size()-1; i >-1; i--){
				delete(i);
			}
		

		   //}catch(ArrayIndexOutOfBoundsException e){
			//	System.out.println("prob" + e);
			//}
	   }
	public void connectionMade(Connection _c, String _address) {

		if (myStorage != null || myByteArray != null) {

			// midletDisplay.setCurrent(this);
			//deleteAll();
			append(mode + " connected " + _address);
			// byte[] allLogs = {65,66,67};
			uploadConnection = _c; // connectionForm.getConnection();
			// System.out.println(myStorage + "Upload Connection Made" + uploadConnection);

			uploadConnection.addListener(this);

			uploads = 0;

			if (myStorage != null) {

				send(myStorage, null, -1, -1);
				midletDisplay.setCurrent(this);

			} else {

				send(myByteArray, null, myByteArray.length, 0, null);
				midletDisplay.setCurrent(this);

			}
			// System.out.println("here");
		} else {
			midletDisplay.setCurrent(revertToForm);
		}
		setPrefs();
	
	}

	public void display(String _s) {
		append(_s);
	}

	public void feedback(Connection _c, String _feedback) {

	}

	public int getContentFormattingStyle() {
		return contentFormattingStyle;
	}

	public int getFilenameInsertionStyle() {
		return filenameInsertionStyle;
	}

	public Vector getNextRecord() {
		Vector returnVector = new Vector();

		Vector recordParts = myStorage.getRecordParts(recordBeingSent);
		long time = ((Long) recordParts.elementAt(0)).longValue();
		returnVector.addElement((Long) recordParts.elementAt(0));

		if (contentFormattingStyle == TIMESTAMP_CONTENTS_METADATA_RAW_BYTES) {
			returnVector.addElement(recordParts.elementAt(3));
			returnVector.addElement(recordParts.elementAt(2)); // no separate metadata
		} else if (contentFormattingStyle == CONTENTS_METADATA_RAW_BYTES) {
			byte[] contents = (byte[]) recordParts.elementAt(1);
			byte[] metadata = (byte[]) recordParts.elementAt(2);
			byte[] combo;
			if (metadata == null) {
				combo = contents;
			} else {
				combo = new byte[contents.length + metadata.length];

				System.arraycopy(contents, 0, combo, 0, contents.length);
				System.arraycopy(metadata, 0, combo, contents.length, metadata.length);
			}
			// System.arraycopy(_byteArray, 0, uploadArray, sizeSoFar, _byteArray.length); sizeSoFar = sizeSoFar + _byteArray.length;
			// public static void arraycopy(Object src,
			// int src_position,
			// Object dst,
			// int dst_position,
			// int length)
			returnVector.addElement(combo);
			returnVector.addElement(recordParts.elementAt(2)); // no separate metadata
		} else if (contentFormattingStyle == CONTENTS_RAW_BYTES) {
			returnVector.addElement(recordParts.elementAt(1));
			returnVector.addElement(recordParts.elementAt(2)); // no separate metadata

		} else if (contentFormattingStyle == TIMESTAMP_CONTENTS_METADATA_ASCII) {
			byte[] metadata = (byte[]) recordParts.elementAt(2);
			String combo = "";
			if  (metadata != null){
				combo = String.valueOf(time) + "," + new String((byte[]) recordParts.elementAt(1)) + "," + new String(metadata);
			}else{
				combo = String.valueOf(time) + "," + new String((byte[]) recordParts.elementAt(1)) ;
			}
			returnVector.addElement(combo.getBytes());
		
			returnVector.addElement(recordParts.elementAt(2)); // no separate metadata
		} else if (contentFormattingStyle == CONTENTS_METADATA_SEPARATE_FILES) {
			returnVector.addElement(recordParts.elementAt(1));
			returnVector.addElement(recordParts.elementAt(2)); // return metadata separately
		}

		return returnVector;
	}

	public int getPacketSize() {
		return packetSize;
	}

	public Preferences getPrefs() {

		try {
			// Storage prefs = new Storage(this.getClass().getName() + ".prefs");
			prefs = new Preferences(this.getClass().getName() + ".prefs");
			String s = prefs.getPref("packetSize");
			if (s != null) packetSize = Integer.parseInt(s);
			s = prefs.getPref("baseFilename");
			if (s != null) baseFilename = new String(s);
			// System.out.println("getPrefBasefilename" + baseFilename);

			s = prefs.getPref("append");
			if (s != null) append = s.equals("true");
			s = prefs.getPref("allowBunching");
			if (s != null) allowBunching = s.equals("true");

			s = prefs.getPref("contentFormattingStyle");
			if (s != null) contentFormattingStyle = Integer.parseInt(s);
			s = prefs.getPref("filenameInsertionStyle");
			if (s != null) filenameInsertionStyle = Integer.parseInt(s);
		} catch (NumberFormatException e) {
			System.out.println("Not a number");
		}
		return prefs;
	}

	public void incoming(Connection _whichConnection, byte[] _input) {
	//	System.out.println("incoming" + new String(_input));
		if (sendingFragments) {
			sendNextFragment();
		} else if (sendingRecords) { // else if (mode == SENDING_HTTP || mode == SENDING_BT || mode == SENDING_SOCKET) {
		
			uploadNext();
		
	
			// mainForm.deleteAll();

		}
		
		append(new String(_input));
	}

	public boolean isAllowBunching() {
		return allowBunching;
	}

	public boolean isAppend() {
		return append;
	}

	public void itemStateChanged(Item thisItem) {
		setVariablesFromInterface();
		setPrefs();
		if (thisItem == connectionType) {
			String menuChoice = "none";
			int choiceNum = ConnectionSettings.getFirstOfMultiple(connectionType);
			if (choiceNum != -1) {
				menuChoice = connectionType.getString(choiceNum);
			}
			boolean[] cflags = new boolean[connectionType.size()];
			connectionType.setSelectedFlags(cflags);

			if (menuChoice.equals("Upload BT")) {
				System.out.println("Upload BT");
				connectionForm = new BTSerialConnectionSettings(this);
				connectionForm.replaceDisplay(midletDisplay); // mode = SENDING_BT;
				append("Connecting...");
			} else if (menuChoice.equals("Upload HTTP")) {
				System.out.println("HTTP");
				connectionForm = new HttpConnectionSettings(this);
				// mode = SENDING_HTTP;

				recordBeingSent = 0;
				connectionForm.replaceDisplay(midletDisplay);
				// midletDisplay.setCurrent(connectionForm.getDisplayable());
				append("Connecting...");
			} else if (menuChoice.equals("Upload Socket")) {
				System.out.println("Upload SOCKET");
				connectionForm = new SocketConnectionSettings(this);
				connectionForm.replaceDisplay(midletDisplay);
				// midletDisplay.setCurrent(connectionForm.getDisplayable());

				// mode = SENDING_BT;
				append("Connecting...");
			//} else if (menuChoice.equals("Go Back")) {
			//	midletDisplay.setCurrent(revertToForm);
			}
		}
	}

	public void send(byte[] _byteArray, String _filename, int _len, long _timestamp, byte[] _metadata) {

		if (_filename == null) _filename = fileNameBox.getString();
		if (_timestamp == 0) _timestamp = System.currentTimeMillis();
		String metadataString = "";
		if (_metadata != null) metadataString = new String(_metadata);
		String adjustedFilename = new String(_filename);
		if (filenameInsertionStyle == INSERT_TIMESTAMP_IN_FILENAME) {
			adjustedFilename = new String(_filename);
			int dot = adjustedFilename.lastIndexOf('.');
			adjustedFilename = adjustedFilename.substring(0, dot) + "-" + String.valueOf(_timestamp) + "." + adjustedFilename.substring(dot + 1, adjustedFilename.length());
		} else if (filenameInsertionStyle == INSERT_TIMESTAMP_METADATA_IN_FILENAME) {
			// System.out.println("Trying to put meta into filename" + _metadata);
			adjustedFilename = new String(_filename);
			int dot = adjustedFilename.lastIndexOf('.');
			adjustedFilename = adjustedFilename.substring(0, dot) + "-" + String.valueOf(_timestamp) + "-" + metadataString + "." + adjustedFilename.substring(dot + 1, adjustedFilename.length());
		} else {
			adjustedFilename = new String(_filename);
		}
		if (contentFormattingStyle == CONTENTS_METADATA_SEPARATE_FILES) {
			packingSlip = new String[6];
			packingSlip[5] = metadataString;
			System.out.println("Adding " + metadataString + " to Packing slip");
		} else {
			packingSlip = new String[5];
		}

		packingSlip[0] = adjustedFilename;
		packingSlip[1] = "REPLACE";
		if (append) {
			packingSlip[1] = "APPEND";
		}
		packingSlip[2] = String.valueOf(_len);
		packingSlip[3] = "1";
		packingSlip[4] = "1";

		if (_len > packetSize && packetSize != -1) { // if they set it too low no records will go through at all

			uploadArray = _byteArray;
			sendingFragments = true;
			placeInUploadArray = 0;
			packetNumber = 0;
			totalPackets = _byteArray.length / packetSize + 1;
			sendNextFragment(); // get the ball
			// flush(); // maybe should wait for this to come back as true

		} else {

			uploadConnection.send(_byteArray, combineStringArray(packingSlip, "|"), _len);

		}
	}

	public void send(Storage _s, String _fileName, int _startRecord, int _endRecord) {
		myStorage = _s;

		if (_fileName != null) {
			fileNameBox.setString(_fileName);
		}

		sendingRecords = true;
		uploadNext();
	}

	public void sendNextFragment() {
		// System.out.println(uploadArray + "Send Next" + packingSlip);

		byte[] thisPacket = new byte[packetSize];
		int payload = Math.min(packetSize, (uploadArray.length - placeInUploadArray));

		System.arraycopy(uploadArray, placeInUploadArray, thisPacket, 0, payload);
		// System.out.println("Send Next Next" + placeInUploadArray);

		// uploadConnection.send(thisPacket, null, sizeSoFar);
		packetNumber++;

		// String infoString = adjustedFilename + "|" + appendText + "|" + payload + "|" + packetNumber + "|" + totalPackets;
		packingSlip[3] = String.valueOf(packetNumber);
		packingSlip[4] = String.valueOf(totalPackets);

		uploadConnection.send(thisPacket, combineStringArray(packingSlip, "|"), payload);
		placeInUploadArray = placeInUploadArray + packetSize;
		if (placeInUploadArray >= uploadArray.length) {
			sendingFragments = false;
			System.out.println("Reached Last Packet");

		}
	}

	public void setAllowBunching(boolean allowBunching) {
		this.allowBunching = allowBunching;
	}

	public void setAppend(boolean append) {
		this.append = append;
	}

	public void setContentFormattingStyle(int contentFormattingStyle) {
		this.contentFormattingStyle = contentFormattingStyle;
		setInterfaceFromVariables();
	}

	public void setFilenameInsertionStyle(int filenameInsertionStyle) {
		this.filenameInsertionStyle = filenameInsertionStyle;
		setInterfaceFromVariables();
	}

	void setInterfaceFromVariables() {
		// reflect it in the interface

		
		
		if (baseFilename.equals("None")) {
			fileNameBox.setString(myStorage.getName());
		} else {
			fileNameBox.setString(baseFilename);
		}
		chunkSize.setString(String.valueOf(packetSize));
		boolean[] flags = new boolean[filenameInsertionChoice.size()];
		for (int i = 0; i < filenameInsertionChoice.size(); i++) {
			if (filenameInsertionStyle == i) {
				flags[i] = true;
				break;
			}
		}
		filenameInsertionChoice.setSelectedFlags(flags);
		
		flags = new boolean[contentFormattingChoice.size()];
		for (int i = 0; i < contentFormattingChoice.size(); i++) {
			if (contentFormattingStyle == i) {
				flags[i] = true;
				break;
			}
		}
		contentFormattingChoice.setSelectedFlags(flags);


		flags = new boolean[uploadStyle.size()];
		flags[1] = allowBunching;
		flags[0] = append;
		uploadStyle.setSelectedFlags(flags);
	
		//contentFormattingChoice.setSelectedFlags(flags);
		/*
		 * boolean[] flags = { append, allowBunching }; uploadStyle.setSelectedFlags(flags); boolean nothing = false; if (!(timeStampRecordAscii || timeStampRecordBin || timeStampFile)) nothing = true; boolean[] tsflags = { nothing, timeStampRecordAscii, timeStampRecordBin, timeStampFile }; insertInFilename.setSelectedFlags(tsflags); nothing = false; if (!(metadataRecordAscii || metadataRecordBin || metadataFile || metadataSeparateFile)) nothing = true; boolean[] mdflags = { nothing, metadataRecordAscii, metadataRecordBin, metadataFile, metadataSeparateFile}; contentFormatting.setSelectedFlags(mdflags);
		 */
	}

	public void setPacketSize(int packetSize) {
		this.packetSize = packetSize;
	}

	public void setPrefs() {

		// System.out.println("setPrefBasefilename" + baseFilename);

		prefs.setPref("baseFilename", baseFilename);
		prefs.setPref("packetSize", packetSize);
		prefs.setPref("append", append);
		prefs.setPref("allowBunching", allowBunching);

		prefs.setPref("filenameInsertionStyle", filenameInsertionStyle);
		prefs.setPref("contentFormattingStyle", contentFormattingStyle);

		prefs.savePrefs();
	}

	public void setVariablesFromInterface() {
		boolean[] checks = new boolean[uploadStyle.size()]; // _recentChoices.size()]; // have to go through this because I used "MULTIPLE"
		baseFilename = fileNameBox.getString();
		uploadStyle.getSelectedFlags(checks);
		append = checks[0];
		allowBunching = checks[1];

		checks = new boolean[filenameInsertionChoice.size()]; // _recentChoices.size()]; // have to go through this because I used "MULTIPLE"

		// insertInFilename.getSelectedFlags(checks);
		filenameInsertionStyle = ConnectionSettings.getFirstOfMultiple(filenameInsertionChoice);
		// timeStampRecordAscii = checks[1];
		// timeStampRecordBin = checks[2];
		// timeStampFile = checks[3];

		if ((append || allowBunching) && filenameInsertionStyle != 0) {
			// timeStampFile = false;
			filenameInsertionStyle = 0;
			filenameInsertionChoice.setSelectedIndex(0, true);
		}
		packetSize = Integer.parseInt(chunkSize.getString());
		// appendTimeStamp = checks[2];

		contentFormattingStyle = ConnectionSettings.getFirstOfMultiple(contentFormattingChoice);

		// checks = new boolean[contentFormatting.size()]; // _recentChoices.size()]; // have to go through this because I used "MULTIPLE"

		// contentFormatting.getSelectedFlags(checks);

		// metadataRecordAscii = checks[1];
		// metadataRecordBin = checks[2];
		// metadataFile = checks[3];
		// metadataSeparateFile = checks[4];
		setPrefs();
	}

	public void showInterface() {
		
		connectionType = new ChoiceGroup("Make Connection", ChoiceGroup.MULTIPLE);

		connectionType.append("Upload BT", null);
		connectionType.append("Upload HTTP", null);
		connectionType.append("Upload Socket", null);
		connectionType.append("Upload UDP", null);
		
		chunkSize = new TextField("Size of Chunks (Bytes):", null, 60, TextField.DECIMAL);
		chunkSize.setString("1");
		fileNameBox = new TextField("Base File Name For Server:", null, 60, TextField.ANY);
		fileNameBox.setString("Sample_Filename.log");
		uploadStyle = new ChoiceGroup("Upload Log Records", ChoiceGroup.MULTIPLE);
		uploadStyle.append("Append Existing File", null);
		uploadStyle.append("Allow Bunching (faster)", null);
		// uploadStyle.append("Or Individually", null);

		filenameInsertionChoice = new ChoiceGroup("Insert Into Filename:", ChoiceGroup.EXCLUSIVE);

		filenameInsertionChoice.append("None", null);
		filenameInsertionChoice.append("TimeStamp (no append/bunch)", null);
		filenameInsertionChoice.append("TimeStamp and Metadata (no append/bunch)", null);

		contentFormattingChoice = new ChoiceGroup("Content Formatting:", ChoiceGroup.EXCLUSIVE);

		contentFormattingChoice.append("T.S. Data Meta Raw Bytes", null);
		contentFormattingChoice.append( "Data Meta Raw Bytes", null);
		contentFormattingChoice.append("Data Raw Bytes", null);
		contentFormattingChoice.append("T.S.,Data,Meta ASCII", null);
		contentFormattingChoice.append("Sep Files(no append/bunch) Data Meta", null);

		
		append(connectionType);
		
		setInterfaceFromVariables();
		
		Command setPreferences = new Command("Preferences", Command.OK, 1);
		Command exit = new Command("Exit", Command.OK, 2);
		addCommand(setPreferences);
		addCommand(exit);
		
		setItemStateListener(this);
		setCommandListener(this);
		//connectionType.append("Go Back", null);
	}

	public void showProtocolOptions(){

	

		append(fileNameBox);
		append(uploadStyle);
		append(chunkSize);
		append("Not all applications have metadata.");
		append(filenameInsertionChoice);
		append(contentFormattingChoice);

		setInterfaceFromVariables();
		// setPrefs();
	}

	public void uploadNext() {

		uploads++;

		if (allowBunching) {

			uploadNextBlockOfRecords(packetSize);
		} else {
			// each record independently
			uploadNextRecord();
		}

	}

	public void finishedUpload(){
		uploadConnection.disconnect();
		midletDisplay.setCurrent(revertToForm);
		System.out.println("Finished");
	}
	public void uploadNextBlockOfRecords(int _size) {
		byte[] uploadArray = new byte[_size];
		int bunchedSoFar = 0;

		int previous = recordBeingSent;
		boolean combining = true;
		if (recordBeingSent >= myStorage.getNumberOfRecords()) {
			combining = false;
			// uploadConnection.disconnect(); get null pointer
			midletDisplay.setCurrent(revertToForm);
			System.out.println("Finished");
		}

		while (combining) {
			if (recordBeingSent < myStorage.getNumberOfRecords()) {
				// byte[] thisRecord = Storage.getRecord(myRecordStore, allRecordIDs[recordBeingSent]); // (byte[]) myRecordStore.getRecord(allRecordIDs[recordBeingSent]);
				Vector recordParts = getNextRecord();
				byte[] thisRecord = (byte[]) recordParts.elementAt(1);
				// don't bother getting the metadata and time stamp beccause we are bunching
				if (thisRecord.length > _size) { // if they set it too low no records will go through at all
					_size = thisRecord.length;
				}
				if (thisRecord.length + bunchedSoFar > _size) {
					break;
				}

				System.arraycopy(thisRecord, 0, uploadArray, bunchedSoFar, thisRecord.length);
				bunchedSoFar = bunchedSoFar + thisRecord.length;
				recordBeingSent++;
			} else {
				break;
			}
		}
		if (bunchedSoFar > 0) {
			//deleteAll();
			append("Transmission: " + uploads);
			append("Records Sent = " + previous + " to " + recordBeingSent);
			// don't fool around with filenames timestamps and metadata if bunched.
			send(uploadArray, null, bunchedSoFar, 0, null);
		}
	}

	public void uploadNextRecord() {

		if (recordBeingSent < myStorage.getNumberOfRecords()) {
			// byte[] thisRecord = Storage.getRecord(myRecordStore, allRecordIDs[recordBeingSent]); // (byte[]) myRecordStore.getRecord(allRecordIDs[recordBeingSent]);
			Vector recordParts = getNextRecord();

			// byte[] thisRecord = (byte[]) myRecordStore.getRecord(allRecordIDs[recordBeingSent]);
			//deleteAll();
			append("Record Sent = " + recordBeingSent);
			recordBeingSent++;
			byte[] thisRecord = (byte[]) recordParts.elementAt(1);
			long timeStamp = ((Long) recordParts.elementAt(0)).longValue();
			// System.out.println("meta " + new String((byte[]) recordParts.elementAt(2)));
			// send(thisRecord, null, thisRecord.length, timeStamp, null);
			send(thisRecord, null, thisRecord.length, timeStamp, (byte[]) recordParts.elementAt(2));

			// try {
			// Thread.sleep(20);
			// } catch (InterruptedException e) {
			// e.printStackTrace();
			// }
		} else {
			finishedUpload();

		}
	}



}

/*
 * public void uploadAllRecords() {
 * 
 * int[] allRecordIDs = Storage.getRecordIDs(myRecordStore); for (int i = 0; i < allRecordIDs.length; i++) { byte[] thisRecord = getRecord(myRecordStore, allRecordIDs[recordBeingSent]); // (byte[]) myRecordStore.getRecord(allRecordIDs[recordBeingSent]);
 * 
 * //byte[] thisRecord = (byte[]) myRecordStore.getRecord(allRecordIDs[i]); deleteAll(); append("Record Sent = " + i); uploadConnection.send(thisRecord);
 * 
 * try { Thread.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
 */
/*
 * public void flush() { if (sizeSoFar > 0) { readyForTransmission = false; deleteAll(); append("Transmission: " + uploads); uploadConnection.send(uploadArray, null, sizeSoFar); sizeSoFar = 0; } else { sendNextFragment(); //get the ball } }
 */

/*
 * public boolean send(byte[] _byteArray, String _info) { boolean[] checks = new boolean[uploadStyle.size()]; // _recentChoices.size()]; // have to go through this because I used "MULTIPLE" uploadStyle.getSelectedFlags(checks); uploads++; if (readyForTransmission == false) return false; String fn = new String(uploadConnection.getFilename()); if (checks[1]) { // send whole if (checks[2]) {
 * 
 * int dot = fn.lastIndexOf('.'); fn = fn.substring(0, dot) + String.valueOf(System.currentTimeMillis()) + "." + fn.substring(dot + 1, fn.length()); if (_byteArray.length > packetSize) { // if they set it too low no records will go through at all uploadArray = _byteArray; sendingFragments = true; placeInFragments = 0; flush(); // maybe should wait for this to come back as true return true; } else { uploadConnection.send(_byteArray, fn); readyForTransmission = false; return true; } } else { if (_byteArray.length > packetSize) { // if they set it too low no records will go through at all uploadArray = _byteArray;
 * 
 * sendingFragments = true; placeInFragments = 0; flush(); // maybe should wait for this to come back as true return true; } if (sizeSoFar == 0) { packetSize = Integer.parseInt(chunkSize.getString()) * 1000; uploadArray = new byte[packetSize]; } if (_byteArray.length + sizeSoFar > packetSize) { flush(); return false; }
 * 
 * System.arraycopy(_byteArray, 0, uploadArray, sizeSoFar, _byteArray.length); sizeSoFar = sizeSoFar + _byteArray.length; } } }
 * 
 * //String packingSlip = adjustedFilename + "|" + appendText +"|" + _len + "|1|1";
 * 
 *  /* // in case they want time stamping but are sending not from a record store if (filenameInsertionStyle == INSERT_TIMESTAMP_IN_FILENAME && myStorage == null) { adjustedFilename = new String(_filename); int dot = adjustedFilename.lastIndexOf('.'); adjustedFilename = adjustedFilename.substring(0, dot) + "-" + String.valueOf(System.currentTimeMillis()) + "." + adjustedFilename.substring(dot + 1, adjustedFilename.length()); System.out.println("array input needs stamping" + adjustedFilename); }
 */
/*
 * //byte[] record = (byte[]) recordParts.elementAt(1); // byte[] metadata = (byte[]) recordParts.elementAt(2); //byte[] wholeRecord =(byte[]) recordParts.elementAt(3);
 *  // if (contentFormattingStyle == RAW_BYTES){
 * 
 * //} // NO_INSERTION_IN_FILENAME; //TIMESTAMP_INSERTION_IN_FILENAME; //TIMESTAMP_METADATA_INSERTION_IN_FILENAME;
 * 
 * //RAW_BYTES; //TIMESTAMP,_CONTENTS,_METADATA_ASCII; //CONTENTS_METADATA_SEPARATE_FILES;; if (filenameInsertionStyle == INSERT_TIMESTAMP_IN_FILENAME){
 * 
 * }else if (filenameInsertionStyle == INSERT_TIMESTAMP_METADATA_IN_FILENAME){
 * 
 * }else{
 *  }
 * 
 * if (contentFormattingStyle == RAW_BYTES){
 * 
 * }else if (contentFormattingStyle == TIMESTAMP_CONTENTS_METADATA_ASCII){
 * 
 * }else if (contentFormattingStyle == CONTENTS_METADATA_SEPARATE_FILES){
 *  }
 * 
 *  /*
 * 
 * //long timeStamp = recordParts if (timeStampRecordBin) { thisRecord = myStorage.getRecordAndStamp(recordBeingSent); } else if (timeStampRecordAscii) { thisRecord = myStorage.getRecord(recordBeingSent); long timeOfRecord = myStorage.getTimeStamp(recordBeingSent); if (timeOfRecord == -2) timeOfRecord = System.currentTimeMillis(); String combined = String.valueOf(timeOfRecord) + "," + new String(thisRecord); thisRecord = combined.getBytes(); } else { thisRecord = myStorage.getRecord(recordBeingSent); } // find out about adding timestamp to filename, communicated to rest of program via adjustedFilename adjustedFilename = new String(fileNameBox.getString()); if (timeStampFile) { if (myStorage.isTimeSTamping() == false) { int dot = adjustedFilename.lastIndexOf('.'); adjustedFilename =
 * adjustedFilename.substring(0, dot) + "-" + String.valueOf(System.currentTimeMillis()) + "." + adjustedFilename.substring(dot + 1, adjustedFilename.length()); System.out.println("time fake" + adjustedFilename); } else { long timeOfRecord = myStorage.getTimeStamp(recordBeingSent); int dot = adjustedFilename.lastIndexOf('.'); adjustedFilename = adjustedFilename.substring(0, dot) + "-" + String.valueOf(timeOfRecord) + "." + adjustedFilename.substring(dot + 1, adjustedFilename.length()); System.out.println("time" + adjustedFilename); } }
 * 
 * 
 * if (metadataRecordBin) { thisRecord = myStorage.getRecordAndStamp(recordBeingSent); } else if (timeStampRecordAscii) { thisRecord = myStorage.getRecord(recordBeingSent); long timeOfRecord = myStorage.getTimeStamp(recordBeingSent); if (timeOfRecord == -2) timeOfRecord = System.currentTimeMillis(); String combined = String.valueOf(timeOfRecord) + "," + new String(thisRecord); thisRecord = combined.getBytes(); } else { thisRecord = myStorage.getRecord(recordBeingSent); } // find out about adding timestamp to filename, communicated to rest of program via adjustedFilename adjustedFilename = new String(fileNameBox.getString()); if (timeStampFile) { if (myStorage.isTimeSTamping() == false) { int dot = adjustedFilename.lastIndexOf('.'); adjustedFilename = adjustedFilename.substring(0, dot) +
 * "-" + String.valueOf(System.currentTimeMillis()) + "." + adjustedFilename.substring(dot + 1, adjustedFilename.length()); System.out.println("time fake" + adjustedFilename); } else { long timeOfRecord = myStorage.getTimeStamp(recordBeingSent); int dot = adjustedFilename.lastIndexOf('.'); adjustedFilename = adjustedFilename.substring(0, dot) + "-" + String.valueOf(timeOfRecord) + "." + adjustedFilename.substring(dot + 1, adjustedFilename.length()); System.out.println("time" + adjustedFilename); } }
 */
// return thisRecord;
// }*/
